<?php

namespace App\Kuafu\Mybank\Validate;

use App\Exceptions\CustomValidateException;
use App\Http\Validate\AbstractBaseValidate;
use App\Kuafu\Mybank\Model\MybankEntryModel;
use App\Kuafu\Mybank\Model\MybankShopBindModel;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Model\User;
use App\Library\Common\CommonTools;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\MessageBag;
use Illuminate\Validation\Rule;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use App\Kuafu\Shop\Model\Shop;

class MybankEntryValidate extends AbstractBaseValidate
{
    /**
     * @inheritDoc
     */
    function getRules(): array
    {
        // TODO: Implement getRules() method.
        return [
            "id" => ["int", "gt:0", Rule::exists((new MybankEntryModel())->getTable(), "id")->where("isDeleted", 0)]
        ];
    }

    /**
     * @inheritDoc
     */
    function getAttributes(): array
    {
        // TODO: Implement getAttributes() method.
        return [
            "id"                         => "商户id",
            "merchantType"               => "商户类型",
            "merchantName"               => "商户名称",
//            "contactMobile"              => "联系人手机号[商户常用联系人联系手机号]",
//            "contactName"                => "联系人姓名[商户常用联系人姓名]",
            "principalMobile"            => "负责人手机号",
            "principalCertType"          => "负责人证件类型",
            "principalCertNo"            => "负责人证件号码",
            "principalPerson"            => "负责人名称或企业法人代表姓名",
            "bussAuthType"               => "证件类型",
            "bussAuthNo"                 => "证件号码",
            "bussAuthVld"                => "营业执照有效期",
            "bindShopList.*"             => "绑定门店",
            "identificationCardLife"     => "身份证有效期",
            "businessLicenseImg"         => "营业执照照片",
            "identificationCardBackImg"  => "身份证背面照",
            "identificationCardFrontImg" => "身份证正面图"
        ];
    }

    /**
     * @inheritDoc
     */
    function registerValidateRules(): void
    {
        // TODO: Implement registerValidateRules() method.
        Validator::extend('identityCardNumber',
            function ($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
                return self::isValid($value);
            }, '身份证号码不合法');

        Validator::extend('mobile', function ($attribute, $value, $parameters, $validator) {
            return $validator->validateRegex(
                $attribute,
                $value,
                ['/^1[3-9]\d{9}$/'],
                "手机号格式非法"
            );
        });

        Validator::extend('customerStringIn',
            function ($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator) {
                if (is_array($value) && $validator->hasRule($attribute, 'Array')) {
                    foreach ($value as $element) {
                        if (is_array($element)) {
                            return false;
                        }
                    }

                    return count(array_diff($value, $parameters)) === 0;
                }

                return !is_array($value) && in_array((string)$value, $parameters, true);
            }, '选定的 商户类型 是无效的');
    }


    /**
     * @inheritDoc
     */
    function getMessages(): array
    {
        // TODO: Implement getMessages() method.
        return [
            "principalMobile.exists" => "负责人手机号未注册rms平台"
        ];
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws CustomValidateException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function detailValidate(array $params)
    {
        return self::getInstance()->validate(["id"], $params);
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws CustomValidateException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function remindActivateValidate(array $params)
    {
        return self::getInstance()->validate(["id"], $params, [
            "id" => [
                "int",
                "gt:0",
                Rule::exists((new MybankEntryModel())->getTable(), "id")
                    ->where("status", MybankEntryModel::STATUS_2)
                    ->where("isDeleted", 0)
            ]
        ]);
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws CustomValidateException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function remindWithholdingValidate(array $params)
    {
        return self::getInstance()->validate(["id"], $params, [
            "id" => [
                "int",
                "gt:0",
                Rule::exists((new MybankEntryModel())->getTable(), "id")
                    ->where("status", MybankEntryModel::STATUS_3)
                    ->where("withholdStatus", MybankEntryModel::WITHHOLD_STATUS_2)
                    ->where("isDeleted", 0)
            ]
        ]);
    }

    /**
     * 创建校验
     *
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws CustomValidateException
     * @throws NotFoundExceptionInterface
     */
    public static function createValidate(array $params)
    {
        $validateFields = [
            "merchantType",
            "merchantName",
//                "contactMobile",
//                "contactName",
            "principalMobile",
            "principalCertNo",
            "principalPerson",
            "bussAuthNo",
            "bussAuthVld",
            "identificationCardLife",
            "businessLicenseImg",
            "identificationCardBackImg",
            "identificationCardFrontImg",
            'from',
        ];

        $validateRules = [
            "merchantType"               => [
                "required",
                "string",
                "customerStringIn:" . self::enumTransToRules(MybankEntryModel::MERCHANT_TYPE_TEXT)
            ],
            "merchantName"               => self::stringValidateBuild(true, 50, 1),
//                "contactMobile"   => "required|mobile",
//                "contactName"     => self::stringValidateBuild(true, 30, 1),
            "principalMobile"            => [
//                    "exclude_unless:merchantType,02",
                "required",
                "mobile",
                Rule::exists((new User())->getTable(), "mobile")->where("status", 0)
            ],
            "principalCertNo"            => "required|identityCardNumber",
            "principalPerson"            => "required|max:120",
            "bussAuthNo"                 => "string|max:256",
            "bussAuthVld"                => "string|max:32",
            "identificationCardLife"     => "required|string|min:1|max:64",
            "businessLicenseImg"         => "url",
            "identificationCardBackImg"  => "url",
            "identificationCardFrontImg" => "url",
            'from'                       => 'string',
        ];

        if (CommonTools::isWebRequest()) {
            $validateFields = array_merge($validateFields, ["bindShopList"]);
            $validateRules  = array_merge($validateRules, [
                "bindShopList"   => "required|array|min:1",
                "bindShopList.*" => [
                    "required",
                    "int",
                    "gt:0",
                    Rule::exists((new Shop())->getTable(), "id"),
                    Rule::unique((new MybankShopBindModel())->getTable(), "shopId")->where("isDeleted", 0)
                ]
            ]);
        }

        return self::getInstance()->validate(
            $validateFields,
            $params,
            $validateRules,
            true,
            function (array $params) {

                if ($params["merchantType"] != MybankEntryModel::MERCHANT_TYPE_01) {
                    $params["businessLicenseImg"] = getFileKey($params["businessLicenseImg"]);
                } else {
                    $params["businessLicenseImg"] = '';
                }

                $params["identificationCardBackImg"]  = getFileKey($params["identificationCardBackImg"]);
                $params["identificationCardFrontImg"] = getFileKey($params["identificationCardFrontImg"]);
                return $params;
            }
        );
    }

    /**
     * 创建校验
     *
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws CustomValidateException
     * @throws NotFoundExceptionInterface
     */
    public static function updateValidate(array $params)
    {
        return self::getInstance()->validate(
            [
                "id",
                "bindShopList"
            ],
            $params,
            [
                "id"             => [
                    "int",
                    "gt:0",
                    Rule::exists((new MybankEntryModel())->getTable(), "id")->where("isDeleted", 0)
                ],
                "bindShopList"   => "required|array|min:1",
                "bindShopList.*" => [
                    "required",
                    "int",
                    "gt:0",
                    Rule::exists((new Shop())->getTable(), "id"),
                    function ($attribute, $value, $fail) use ($params) {
                        $exists = MybankShopBindModel::query()
                                                     ->where("entryId", "<>", $params["id"])
                                                     ->where("shopId", $value)
                                                     ->where("isDeleted", 0)->exists();
                        if ($exists) {
                            $fail("选定的门店 {$attribute} 已被绑定");
                        }
                    }
                ]
            ]
        );
    }

    /**
     * @param array $params
     * @return MessageBag|object
     * @throws ContainerExceptionInterface
     * @throws CustomValidateException
     * @throws NotFoundExceptionInterface
     */
    public static function confirmArrangementValidate(array $params)
    {
        return self::getInstance()->validate(["id"], $params, [
            "id"          => [
                "int",
                "gt:0",
                Rule::exists((new MybankEntryModel())->getTable(), "id")
                    ->where("status", MybankEntryModel::STATUS_3)
                    ->where("withholdStatus", MybankEntryModel::WITHHOLD_STATUS_4)
                    ->where("isDeleted", 0)
            ],
            "auditResult" => "required|string|in:AGREE,REJECT"
        ]);
    }
}
